package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto) {
        dishService.add(dishDto);
        //添加菜品 清理缓存
        //设置key---清理当前的菜品分类下的缓存
//        String key = "dish"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);

        //设置key---清理所有的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("保存成功");
    }

    /**
     * 分页展示菜品
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        Page<Dish> result = dishService.page(pageInfo, queryWrapper);

        //根据结果获取当前页数据
        List<Dish> dishes = result.getRecords();
        //将当前集合的内容写入新集合
        List<Dish> dishDtos = dishes.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId();
            //根据categoryId获取category对象
            Category category = categoryService.getById(categoryId);
            //获取categoryName
            String categoryName = category.getName();
            //创建dishDto对象
            DishDto dishDto = new DishDto();
            //copy
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(categoryName);
            //返回新集合对象
            return dishDto;
            //collect收集成一个新的集合
        }).collect(Collectors.toList());
        //将返回的结果存储的dish换成dishDto对象
        result.setRecords(dishDtos);
        return R.success(result);

       /* //获取分页展示结果的数据
        List<Dish> dishes = result.getRecords();
        //创建新的集合 存储封装好的dishDto对象
        //父类引用指向子类对象
        List<Dish> dishDtos = new ArrayList<>();
        //根据数据获得categoryId
        for (Dish dish : dishes) {
            Long categoryId = dish.getCategoryId();
            //根据categoryId获取Category对象
            Category category = categoryService.getById(categoryId);
            //根据category获取CategoryName
            String categoryName = category.getName();
            //将dish和categoryName封装到dishDto中
            DishDto dishDto = new DishDto();
            //使用工具类--将dish中的属性复制到dishDto中
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setCategoryName(categoryName);
            dishDtos.add(dishDto);
        }
        //将返回结果中原有的dish集合换成新的dishDtos集合对象
        result.setRecords(dishDtos);
        //将结果响应给前端
        return R.success(result);*/
    }

    /**
     * 修改回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R select(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(flavors);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        dishService.updateByIdWithDishFlavor(dishDto);
        //设置key---清理所有的缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success(dishDto);
    }

    /**
     * 根据分类id查看菜品和口味
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R list(Dish dish) {

        List<DishDto> dishDtos = null;
        //设置key
        String key = "dish_" + dish.getCategoryId() + "_1";
        //先查找redis --有缓存--直接将结果返回
        dishDtos= (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断
        if (dishDtos != null){
            return R.success(dishDtos);
        }

        //redis没有缓存--查询数据库
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", dish.getCategoryId());
        queryWrapper.orderByAsc("sort").orderByDesc("update_time");
        queryWrapper.eq("status", 1);
        List<Dish> dishes = dishService.list(queryWrapper);
        //显示菜品口味信息
        dishDtos = dishes.stream().map((dish1) -> {
            DishDto dishDto = new DishDto();
            //将dish的基本信息保存到dishDto中
            BeanUtils.copyProperties(dish1, dishDto);
            //获取dish对应的口味信息封装到dishDto中
            Long dish1Id = dish1.getId();
            //根据菜品id获取
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            //select * from dishflavor where dishId = ?
            wrapper.eq(DishFlavor::getDishId, dish1Id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //查询到之后 将数据缓存到redis中
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }

}
